package com.guan.servicemsm.controller;

import com.guan.commonutils.R;
import com.guan.servicemsm.service.MsmService;
import com.guan.servicemsm.utils.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Date: 2023/4/18 9:55
 * @Author: 管奇安
 * @Description:
 */

@RestController
@RequestMapping("/msmservice/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){

        //1. 从redis获取验证码
        String codeInRedis = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isNotBlank(codeInRedis)){
            return R.ok();
        }

        //生成随机验证码 传递阿里云进行发送
        String code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);

        //调用发送短信的方法
        boolean isSend = msmService.send(param,phone);

        if (isSend){
            //将验证码存到redis ，有效时间： 5 分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("短信发送失败");
        }


    }



}
